
import ApiBoss from "@/api/boss"
import ApiCrm from "@/api/crm"
import { getToken } from "@/api/token"
import ListView from "@/components/app/ListView"
import PopupContainer from "@/components/app/PopupContainer"
import ByButton from "@/components/ui/ByButton"
import ByCell from "@/components/ui/ByCell"
import ByCellGroup from "@/components/ui/ByCellGroup"
import ByIcon from "@/components/ui/ByIcon"
import ByPopupBottom from "@/components/ui/ByPopupBottom"
import BySearchBar from "@/components/ui/BySearchBar"
import useFetch from "@/hooks/useFetch"
import useList from "@/hooks/useList"
import useAppStore from "@/store"
import setting from "@/utils/setting"
import { Navigator, Picker, ScrollView, Text, View, WebView } from "@tarojs/components"
import { isUndefined } from "@tarojs/shared"
import { useRouter } from "@tarojs/taro"
import { useBoolean, useReactive, useUpdateEffect } from "ahooks"
import dayjs from "dayjs"
import { useState } from "react"


type Item = {
  display_name: string
  default_value: string
  is_allow_edit: boolean
  is_allow_empty: boolean
  parameter_name: string
  parameter_id: number
  value_type: string
  report_id: number
}


const CellDate = ({ value, onChange, label }: {
  value: string
  label: string
  onChange: (e: string) => void
}) => {

  return (
    <Picker mode="date" value={value} onChange={e => onChange(e.detail.value)}>
      <ByCell label={label} labelWidth="5em" next>
        {value}
      </ByCell>
    </Picker>
  )
}

const CellCustomer = ({ isAddress, label, value, valueText, onChange, }: {
  value: string
  label: string
  isAddress?: boolean
  valueText?: string
  onChange: (e: any, text: string) => void
}) => {

  const [boolean, { setFalse, setTrue }] = useBoolean();

  const [search, setSearch] = useState<{}>({ isIntentCustomer: 1 })
  const { loading, list, nextPage, resetToFirst } = useList<any>(ApiCrm.customerList, { defaultParams: [search] })

  useUpdateEffect(() => {
    resetToFirst(search)
  }, [search])


  const handleClick = (item) => {
    if (isAddress) {
      onChange(item.decorationFullAddress, item.decorationFullAddress)
    } else {
      onChange(item.intentCustomerId, item.customerName)
    }

    setFalse()
  }

  return (
    <>
      <ByCell label={label} labelWidth="5em" next onClick={setTrue}>
        {valueText ?? value ?? '请选择'}
      </ByCell>

      {
        boolean &&
        <ByPopupBottom title="选择" onCancel={setFalse}>

          <BySearchBar placeholder="客户名称搜索"
            onClear={() => setSearch({ ...search, customerName: undefined })}
            onConfirm={e => setSearch({ ...search, customerName: e })} />

          <ScrollView scrollY={true} className="h-[60vh]" onScrollToLower={nextPage}>
            <ListView loading={loading} isEmpty={list.length === 0}>
              {
                list.map(item => (
                  <View key={item.id} className="py-3 px-6 border-t-1 border-[#eee]"
                    onClick={() => handleClick(item)}>
                    <View className="">{item.customerName}</View>
                    <View className="mt-1 text-xs">{item.decorationFullAddress}</View>
                  </View>
                ))
              }
            </ListView>
          </ScrollView>
        </ByPopupBottom>
      }
    </>
  )
}

const getDate = (type: string) => {
  const date = dayjs()
  switch (type) {
    case "本月初": return date.startOf('month');
    case "本月末": return date.endOf('month');
    default: return date;
  }
}

const Cell = ({ source, model }: { source: Item, model: {} }) => {
  const { value_type: type, display_name, parameter_name: name } = source

  const props = {
    label: display_name,
    value: model[name],
    labelWidth: "5em"
  }

  const hendleChange = (val: any, text?: string) => {
    model[name] = val
    if (!isUndefined(text)) {
      model["_" + name] = text
    }
  }

  const text = model["_" + name] || model[name]
  return (
    type === '日期' ?
      <CellDate {...props} onChange={hendleChange} /> :

      type === '客户' ?
        <CellCustomer {...props} isAddress={display_name == "项目地址"} valueText={text} onChange={hendleChange} /> :

        <ByCell {...props}>{text}</ByCell>
  )
}


export default () => {

  const { params } = useRouter<{
    id: `${number}`
  }>()

  const id = +params.id
  const token = getToken()

  const model = useReactive({})
  const userInfo = useAppStore(state => state.userInfo)

  const { data } = useFetch<{
    report_detail: Item[]
  }>(ApiBoss.getReportDetail, { defaultParams: [{ report_id: id }] })


  useUpdateEffect(() => {
    const list = data?.report_detail || []
    if (list?.length > 0) {

      list.forEach((e) => {
        const { default_value, value_type, parameter_name } = e
        if (value_type === "日期") {

          model[parameter_name] = getDate(default_value).format("YYYY-MM-DD")
        } else if (value_type === "用户") {
          model[parameter_name] = userInfo?.user_id
          model[`_${parameter_name}`] = userInfo?.user_name
        }
      })
    }
  }, [data])

  const [query, setQuery] = useState("")
  const handleSubmit = () => {

    const data = {}

    Object.keys(model).forEach(key => {
      if (!key.startsWith("_")) {
        data[key] = model[key]
      }
    })

    setQuery(encodeURIComponent(JSON.stringify(data)))
  }
  return (
    <View>

      {
        !query && <>
          <ByCellGroup className="m-4">
            {
              data?.report_detail.map(item => (
                <Cell source={item} model={model} key={item.parameter_id} />
              ))
            }
          </ByCellGroup>

          <ByButton
            size="large"
            className="mx-4 my-6"
            onClick={handleSubmit}
          >查询</ByButton>
        </>
      }

      {
        query && <WebView src={`${setting.webUrl}/statistic/${id}?json=${query}&token=${token}`} />
      }

    </View>
  )
}
